package com.zq.controller;

import com.zq.po.UserPO;
import com.zq.service.impl.UserService;
import com.zq.utils.TokenUtil;

import com.zq.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("test")
public class TestController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    @GetMapping("hello")
    public ResultVo<Object> hello(){
        return ResultVo.success("Hello");
    }

    @GetMapping("world")
    public ResultVo<Object> world(){
        return ResultVo.success("world");
    }

    @PostMapping("login")
    public ResultVo<Object> login(String username,String password){
        //TODO
        UserPO userPO = userService.queryUserByName(username);
        if(userPO==null)
            return ResultVo.fail("用户不存在");
        String token = TokenUtil.createToken(userPO.getId(), username, 2L * 60 * 60 * 1000);
        redisTemplate.opsForValue().set("user:token:"+userPO.getId(),token,2*60, TimeUnit.MINUTES);
        Map<String,String> map=new HashMap<>();
        map.put("token",token);
        return ResultVo.success("登录成功",map);
    }
    @GetMapping("user")
    @RequiresRoles("user")
    public ResultVo<Object> user(){
        return ResultVo.success("访问uer成功");
    }

    @GetMapping("add")
    @RequiresPermissions("user:add")
    public ResultVo<Object> add(){
        return ResultVo.success("访问add成功");
    }

    @GetMapping("delete")
    @RequiresPermissions("user:delete")
    public ResultVo<Object> delete(){
        return ResultVo.success("访问delete成功");
    }

    @GetMapping("insert")
    @RequiresRoles("admin")
    public ResultVo<Object> insert(){
        System.out.println(SecurityUtils.getSubject().hasRole("admin"));
        return ResultVo.success("访问insert成功");
    }

    @GetMapping("in")
    @RequiresAuthentication
    public ResultVo<Object> in(){
        return ResultVo.success("访问in成功");
    }
}
